function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

export async function stream(readable, res) {
  const reader = readable.getReader();
  const encoder = new TextEncoder();
  const decoder = new TextDecoder();
  const delimiter = "\n\n";
  const encodedNewline = encoder.encode("\n");

  let buffer = "";
  while (true) {
    let { value, done } = await reader.read();
    if (done) {
      break;
    }
    buffer += decoder.decode(value, { stream: true }); // stream: true is important here,fix the bug of incomplete line
    let lines = buffer.split(delimiter);

    // Loop through all but the last line, which may be incomplete.
    for (let i = 0; i < lines.length - 1; i++) {
      res.write(lines[i] + delimiter);
      await sleep(30);
    }
    buffer = lines[lines.length - 1];
  }

  if (buffer) {
    res.write(buffer);
  }
  res.write(encodedNewline);
  res.end();
}
